import datetime
import os
import logging.config
from flask import Flask, Blueprint
from patch_tracking import settings
from patch_tracking.api.endpoints.tracking import ns as tracking_namespace
from patch_tracking.api.endpoints.issue import ns as issue_namespace
from patch_tracking.api.restplus import api
from patch_tracking.database import db
from patch_tracking.task import task_apscheduler, task
from patch_tracking.task import scheduler
from patch_tracking.settings import SCAN_DB_INTERVAL

logging_conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__), 'logging.conf'))
logging.config.fileConfig(logging_conf_path, disable_existing_loggers=False)

app = Flask(__name__)
logger = logging.getLogger(__name__)


def configure_app(flask_app):
    flask_app.config['SERVER_NAME'] = settings.FLASK_SERVER_NAME
    flask_app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI
    flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = 'list'
    flask_app.config['ERROR_404_HELP'] = False
    flask_app.config['RESTX_MASK_SWAGGER'] = False
    flask_app.config['SCHEDULER_API_ENABLED'] = True
    flask_app.config['SCHEDULER_EXECUTORS'] = {'default': {'type': 'threadpool', 'max_workers': 100}}


def initialize_app(flask_app):
    configure_app(flask_app)

    blueprint = Blueprint('', __name__, url_prefix='/')
    api.init_app(blueprint)
    api.add_namespace(tracking_namespace)
    api.add_namespace(issue_namespace)
    flask_app.register_blueprint(blueprint)

    db.init_app(flask_app)
    scheduler.init_app(flask_app)


def get_yaml_to_db(flask_app):
    with flask_app.app_context():
        new_track = task_apscheduler.get_track_from_db()
        task.load(new_track)


def main():
    scheduler.add_job(
        id='Add Tracking job - Update DB',
        func=get_yaml_to_db,
        trigger='interval',
        args=(app, ),
        seconds=int(SCAN_DB_INTERVAL),
        next_run_time=datetime.datetime.now()
    )
    scheduler.start()
    logger.info('>>>>> Starting server at http://%s/ <<<<<', app.config['SERVER_NAME'])
    app.run()


initialize_app(app)

if __name__ == "__main__":
    main()
